package logger

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
)

// Logger is the instance of logrus.Logger that we will use throughout the application.
var Logger *logrus.Logger

// Get returns the initialized logger instance.
func InitLog() *logrus.Logger {
	logDir := "logs/applog.log"
	Init(logDir)
	return Logger
}

// Init initializes the logrus logger with file and console outputs.
// It sets up log rotation based on daily schedule and writes logs to both
// the console and a file.
func Init(logPath string) {
	// Create a new logger instance
	Logger = logrus.New()

	// Set log level
	// Set log level

	Logger.SetLevel(logrus.InfoLevel)

	// Set formatter for log entries
	Logger.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
	})

	// Ensure the log directory exists
	logDir := filepath.Dir(logPath)
	if _, err := os.Stat(logDir); os.IsNotExist(err) {
		if err := os.MkdirAll(logDir, 0755); err != nil {
			fmt.Printf("Failed to create log directory: %v\n", err)
			return
		}
	}

	// Configure file log output with log rotation
	logFile, err := rotatelogs.New(
		logPath+".%Y%m%d.log",
		rotatelogs.WithLinkName(logPath),
		rotatelogs.WithRotationTime(24*time.Hour),
		rotatelogs.WithRotationCount(7),
	)
	if err != nil {
		fmt.Printf("Failed to setup log rotation: %v\n", err)
		return
	}

	// Set output to both console and file
	Logger.SetOutput(io.MultiWriter(os.Stdout, logFile))
}
